package com.flx.sys.service;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.log;

import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import groovy.util.logging.Slf4j;

/**
 * @author zm
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private Session session;
	/**
	 * 存放session
	 */
	private static CopyOnWriteArraySet<WebSocket> webSocketSet  = new CopyOnWriteArraySet<>();
	
	/**
	 * 打开
	 * @param session
	 */
	@OnOpen
	public void opOpen(Session session){
		this.session  = session;
		webSocketSet.add(this);
		logger.info("【websocket消息】 有新的连接，总数：{}" + webSocketSet.size());
	}
	
	/**
	 * 关闭
	 */
	@OnClose
	public void onClose(){
		webSocketSet.remove(this);
		logger.info("【websocket消息】 连接断开，总数：{}" + webSocketSet.size());
	}
	
	/**
	 * 消息
	 */
	@OnMessage
	public void onMessage(String message){
		logger.info("【websocket消息】收到客户端发来的消息：{}" + message);
	}
	
	public void sendMessage(String message){
		for(WebSocket webSocket:webSocketSet){
			logger.info("【websocket消息】广播消息，message={}" + message);
			try {
				webSocket.session.getBasicRemote().sendText(message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
